<template>
  <div class="template-content">
    <div class="form-auth-key">
      <Form :model="sysConfig" label-position="right" :label-width="100">
        <FormItem :label="$t('map_mode')">
          <RadioGroup v-model="mapMode" >
            <Radio :disabled="!canEdit" label="ONLINE" border >{{$t('online')}}</Radio>
            <Radio disabled label="OFFLINE" border>{{$t('offline')}}</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem :label="$t('map_name')">
          <span style="margin-right: 10px">{{mapName}}</span>
          <Button type="primary"  :disabled="!canEdit" @click="openSelectMap">{{$t('map_select')}}</Button>
        </FormItem>
        <FormItem :label="$t('map_centre')" >
          <div style="display: flex">
            <Input disabled v-model="sysConfig.MAP_CENTER_POSITION"
                   placeholder="$t('longitude_latitude')"
                   enter-button="$t('map')"
                   @on-search="openMap"
                   style="width:500px"
            ></Input>
            <Button type="primary" :disabled="!canEdit" @click="openMap">{{$t('map')}}</Button>
          </div>
          <Row>
            <Col span="24">

            </Col>
          </Row>
        </FormItem>
        <FormItem :label="$t('map_grade')" >
          <Input disabled v-model="sysConfig.MAP_LEVEL" placeholder="最小,最大 (在线1，23，离线3-下载的级别)"
                 style="width:200px"></Input>
        </FormItem>
        <FormItem :label="$t('coordinate_system')" >
          <Input disabled v-model="sysConfig.MAP_COORD_INFO" :placeholder="$t('coordinate_system')" style="width:200px"></Input>
        </FormItem>
        <FormItem label="LOGO" >
          <Upload
            v-if="canEdit"
            :before-upload="handleUpload"
            accept=".jpg,.png,.bmp,.jpeg"
            action="//jsonplaceholder.typicode.com/posts/">
            <Button icon="ios-cloud-upload-outline">{{$t('pic_select')}}</Button>
          </Upload>

          <img ref="logoImg" src="" left="10" height="48" width="48"/>
        </FormItem>
        <FormItem :label="$t('title')" v-show="!isEnglish" >
          <Input :disabled="!canEdit" v-model="sysConfig.CUSTOMER_TITLE" :placeholder="$t('title')"></Input>
        </FormItem>
        <FormItem :label="$t('title')" v-show="isEnglish" >
          <Input  :disabled="!canEdit" v-model="sysConfig.CUSTOMER_TITLE_ES" placeholder="$t('title')"></Input>
        </FormItem>

        <FormItem :label="$t('cluster_intercom_account')">
          <Row :gutter="2">
            <Col span="12">
              <Form><FormItem >
                <Input style="width: 250px" :disabled="!canEdit" v-model="sysConfig.GROUP_TALK_USER" :placeholder="$t('cluster_intercom_account')"></Input>
              </FormItem></Form>
            </Col>

            <Col span="12">
              <Form :label-width="130"><FormItem :label="$t('cluster_intercom_password')">
                <Input style="width: 250px" type="password" :disabled="!canEdit" v-model="sysConfig.GROUP_TALK_PSWD" :placeholder="$t('cluster_intercom_password')"></Input>
              </FormItem></Form>
            </Col>
          </Row>

        </FormItem>

        <FormItem>
          <Button :disabled="!canEdit" type="primary" @click="update()">{{$t('save')}}</Button>
        </FormItem>
      </Form>
    </div>
    <Modal v-model="map.show" :title="mapTitle" width="730px"  :mask-closable="false"  :footer-hide=true >
      <div style="height: 40px;display: flex">
        <Input disabled v-model="map.dragPos"></Input>
        <Button type="primary" @click="ok" style="margin-left: 5px">{{$t('ok')}}</Button>
        <Button type="default" @click="cancel">{{$t('cancel')}}</Button>
      </div>
      <div id="centerPointMap" ref="centerPointMap" style="height:500px;width:700px;background-color: #3caf36"></div>
    </Modal>

    <Modal v-model="mapSelect.show" :title="mapSelect.title" width="400px"  :mask-closable="false"  :footer-hide=true >
      <div style="height: 100px;display: flex;flex-direction: column">
        <Cascader :data="mapSelect.mapVendor" v-model="mapSelect.value"></Cascader>
        <br></br>
        <div style="display: flex;flex-direction: row-reverse">
          <Button type="default" @click="selectCancel">{{$t('cancel')}}</Button>
          <Button type="primary" @click="selectOk" style="margin-right: 10px">{{$t('ok')}}</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import { findAll,updateAll } from '@/api/sysconfig'
import {mapMutations} from "vuex";
import {apiResult, clone, getLoginUser} from '@/libs/util'
import MapInfo from "@/view/Home/map/maptools/data/MapInfo";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import {solveGps} from "@/view/Home/map/maptools/tool/GpsUtils";
import {dragMap} from "@/view/System/DragTool"
import MapToolsData from "@/view/Home/map/maptools/data/MapToolsData";
export default {
  name: 'SysConfig',
  components:{},
  computed: {
    loginName() {
      /**
       *  computed 就不需要在 data 声明loginName了
       * 取 /store/moudle/login.js 里 getLoginName, 后不用带()*/
      return userLoginName;
    },
    logo(){
      return{
        maxSize:1200,
        fileSize:0,
        file:null,
        base64: null,
        msg: this.$t('pic_must_be_less_than_1K')
      }
    },

    mapTitle(){
      return this.$t('map_locate_select');
    },
  },
  data () {
    return {
      mapMode:"ONLINE",
      mapName:null,
      mapSelect:{
        mapVendor:[],
        show:false,
        title:null,
        value:null
      },
      sysConfig: {
        MAP_CENTER_POSITION: null, //地图中心点
        MAP_MODE: 'ONLINE', //在线/离线  ONLINE,OFFLINE
        MAP_LEVEL: null,
        MAP_COORD_INFO: null,
        MAP_NAME: "GaoDe",
        MAP_SUB_NAME: "GaoDeSL",
        MAP_DEFAULT_ZOM: 14,
        CUSTOMER_LOGO: null,
        CUSTOMER_TITLE: "",
        CUSTOMER_TITLE_ES: "English Ttile",
        GROUP_TALK_USER: "",
        GROUP_TALK_PSWD: ""
      },
      canEdit:true,
      map:{
        dragPos:null,
        centerPos:[],
        //title:this.$t('map_locate_select'),
        show:false,
        mapInfo:null,
        customLayers:{
          layerVector: new LayerVector(),
          sourceVector: new SourceVector(),
        },
        mapObj:null
      },
      isEnglish:false,
    }

  },
  mounted() {
    this.getData();
    this.$nextTick(()=>{
      const userInfo = getLoginUser();//this.$store.getters.getUserInfo;
      const userLoginName=!!userInfo?userInfo.loginName:"";//  this.$store.getters.getFullName;
      this.canEdit = userLoginName == "admin" || userLoginName == "super";
    })

    const mapData = new MapToolsData();
    this.mapSelect.title = this.$t('map_select');
    this.mapSelect.mapVendor=[];
    const _this = this;
    mapData.customMaps.forEach(par=>{
      let mapVen={}
      mapVen['value']=par.name
      mapVen['label']=par.desc
      mapVen['coordinateType']=par.coordinateType
      mapVen['projection']=par.projection
      mapVen['minZoom']=par.minZoom
      mapVen['maxZoom']=par.maxZoom
      mapVen['children']=[]
      _this.mapSelect.mapVendor.push(mapVen);
      par.sub.forEach(item=>{
        let child={}
        child['value']=item.name
        child['label']=item.desc
        mapVen.children.push(child);
      })
    })

    //是否英文
    this.isEnglish=this.$i18n.locale === "en-US";
    //console.log(this.mapSelect.mapVendor)
  },
  methods: {
    ...mapMutations([
      'setSysConfig',
    ]),
    openSelectMap(){
      this.mapSelect.show = true;
    },
    selectOk(){
      //console.log(this.mapSelect.mapVendor);
      //console.log(this.mapSelect.value);
      if (!!this.mapSelect.value && this.mapSelect.value.length >0 ){
        const parValue = this.mapSelect.value[0];
        const childValue = this.mapSelect.value[1];
        this.mapSelect.mapVendor.forEach(par=>{
          if (par.value === parValue){
            this.sysConfig.MAP_LEVEL = par.minZoom + "," + par.maxZoom;
            this.sysConfig.MAP_COORD_INFO = par.coordinateType;
            this.sysConfig.MAP_NAME = parValue;
            this.sysConfig.MAP_SUB_NAME = childValue;
            this.mapName = par.label;
            par.children.forEach(item=>{
              //console.log("item=%o;childValue=%o",item,childValue)
              if (item.value===childValue){
                this.mapName = this.mapName + '/' + item.label;
              }
            })
          }
        })
      }
      this.mapSelect.show = false;
    },
    selectCancel(){
      this.mapSelect.show = false;
    },
    ok(){
      this.map.show = false;
      this.sysConfig.MAP_CENTER_POSITION = this.map.dragPos;
      this.sysConfig.MAP_COORD_INFO = this.map.mapInfo.coordinateType;
      this.sysConfig.MAP_LEVEL = this.map.mapInfo.minZoom + "," + this.map.mapInfo.maxZoom;
    },
    cancel(){
      this.map.show = false;
    },
    openMap(){
      this.map.show=true;
      this.map.mapInfo = new MapInfo().get();
      if (!(!!this.sysConfig.MAP_CENTER_POSITION)){
        this.sysConfig.MAP_CENTER_POSITION = "113.8417658402197,22.612941389571";
      }
      if (!(!!this.sysConfig.MAP_COORD_INFO)){
        this.sysConfig.MAP_COORD_INFO = "WGS84";
      }
      const pos1 = this.sysConfig.MAP_CENTER_POSITION.split(",");
      let pos = [];
      pos.push(parseFloat(pos1[0]));
      pos.push(parseFloat(pos1[1]));
      //坐标系转换
      const gpsData = solveGps(this.sysConfig.MAP_COORD_INFO,pos[1],pos[0]);
      if (!!gpsData){
        pos[0]=gpsData.lon;
        pos[1]=gpsData.lat;
      }
      //地图
      this.map.dragPos = this.sysConfig.MAP_CENTER_POSITION;
      this.map.centerPos = pos;
      if (this.map.show){
        this.$nextTick(()=>{
          this.newMap();
        })
      }
    },
    getData () {
      findAll().then(res => {
        apiResult(res.data,false,result=>{
          this.sysConfig = result.data;
          if (this.sysConfig.MAP_MODE != null && this.sysConfig.MAP_MODE != 'undefined'){
            this.mapMode = this.sysConfig.MAP_MODE;
            //this.mapMode = this.sysConfig.MAP_MODE == 'ONLINE'?this.$t('online'):this.$t('offline');
          }else {
            this.mapMode = 'ONLINE';//this.$t('online');
          }
          if (!!this.sysConfig.CUSTOMER_LOGO){
            this.calcFileSize(this.sysConfig.CUSTOMER_LOGO);
            this.$refs.logoImg.src = this.sysConfig.CUSTOMER_LOGO;
          }

          const mapData = new MapToolsData();
          mapData.customMaps.forEach(par=>{
            if (par.name === this.sysConfig.MAP_NAME){
              this.mapName = par.desc;
              par.sub.forEach(item=>{
                if (item.name === this.sysConfig.MAP_SUB_NAME){
                  this.mapName = this.mapName + "/" + item.desc;
                }
              })
            }
          })
        });
      })
    },

    /**
     * 保存
     */
    update(){
      if (this.logo.maxSize <= this.logo.fileSize){
        this.$Message.error(this.logo.msg);
        return;
      }
      //this.sysConfig.MAP_SUB_NAME="GaoDeSL";
      this.sysConfig.MAP_MODE=this.mapMode==this.$t('offline')?'OFFLINE':'ONLINE';
      //console.log(">>> SysConfig.update sysConfig=%o",this.sysConfig);
      updateAll(JSON.stringify(this.sysConfig)).then(res => {
        apiResult(res.data,true,result=>{
          //this.$Message.success(result.msg)
          this.setSysConfig(clone(this.sysConfig));
          new MapInfo().setFromApi();
        });
      })
    },
    /**
     * 文件上传前的处理
     */
    handleUpload(){
      this.logo.file = event.target.files[0];
      this.imageToBase64(this.logo.file).then(
        res=>{
          console.log("res=%o",res);
          //显示图片
          this.sysConfig.CUSTOMER_LOGO=res;
          this.$refs.logoImg.src = res;
          this.logo.base64 = res;

          //计算文件实际长度，
          // 1去头 data:image/png;base64,
          // 去尾，==
          // 再计算
          this.calcFileSize(res);

          this.sysConfig.CUSTOMER_LOGO = this.logo.base64;
        },
        err=>{
          console.log(err);
          this.$Message.error(err);
        }
      )
      return false;
    },

    /**
     * 由base64计算文件大小
     */
    calcFileSize(base64){
      let equalIndex = base64.indexOf(',');
      if(equalIndex>0) {
        base64=base64.substring(equalIndex+1, base64.length);
      }
      //console.log(res);
      equalIndex = base64.indexOf('=');
      if(equalIndex>0) {
        base64=base64.substring(0, equalIndex);
      }
      //console.log(res);
      const strLength=base64.length;
      this.logo.fileSize = (strLength/8)*2;

      return this.logo.fileSize;
    },

    /**
     * 使用 fetch API 将图片文件转为 base64 格式
     */
    imageToBase64(file) {
      return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
          reader.readAsDataURL(file);
      });
    },
    newMap(){
      console.log(">>>>> SysConfig.newMap() >>>>>>>>>> ")
      const that = this;
      dragMap("centerPointMap",
        this.map.centerPos,
        this.map.mapInfo,
        (coordinate)=>{
          that.map.dragPos = coordinate;
        },
      );
    },
  }
}
</script>

<style lang="less">
@import ".././template";
#mapcantaner{
  position: absolute;
  top:200px;
  left: 200px;
  z-index: 100;
}
</style>
